//
//  WJPurchaseManager.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/10/3.
//

import UIKit
import StoreKit

enum WJSku: String, CaseIterable {
    case yearlyDiscount = "com.sign.pdf.sigmax.yearly1"
    case yearly = "com.sign.pdf.sigmax.yearly2"
    case weeklyFree = "com.sign.pdf.sigmax.weekly1"
    case weekly = "com.sign.pdf.sigmax.weekly2"
    case weeklyDiscount = "com.sign.pdf.sigmax.weekly3"
    
    init?(rawValue: String) {
        switch rawValue {
        case "com.sign.pdf.sigmax.yearly2":
            self = .yearly
        case "com.sign.pdf.sigmax.yearly1":
            self = .yearlyDiscount
        case "com.sign.pdf.sigmax.weekly2":
            self = .weekly
        case "com.sign.pdf.sigmax.weekly1":
            self = .weeklyFree
        case "com.sign.pdf.sigmax.weekly3":
            self = .weeklyDiscount
        default:
            return nil
        }
    }
}

// 内购状态枚举
enum WJPurchaseResult {
    case success(receipt: String)
    case failure(error: String)
    case restoreFailure(error: String)
    case cancelled
    case restored
}

protocol WJPurchaseManagerDelegate: AnyObject {
    func productsLoaded(products: [SKProduct])
    func purchaseCompleted(result: WJPurchaseResult)
    func productsRequestFailed(error: String)
}

class WJPurchaseManager: NSObject {
    
    // MARK: - 单例
    static let shared = WJPurchaseManager()
    
    // MARK: - 属性
    weak var delegate: WJPurchaseManagerDelegate?
    private var availableProducts: [SKProduct] = []
    private var productIdentifiers: Set<String> = []
    
    // MARK: - 初始化
    private override init() {
        super.init()
        setupPaymentObserver()
    }
    
    deinit {
        SKPaymentQueue.default().remove(self)
    }
    
    // MARK: - 设置支付监听
    private func setupPaymentObserver() {
        SKPaymentQueue.default().add(self)
    }
    
    // MARK: - 获取产品信息
    func fetchProducts(identifiers: Set<String>) {
        self.productIdentifiers = identifiers
        
        guard !identifiers.isEmpty else {
            delegate?.productsRequestFailed(error: "product identifier is empty")
            return
        }
        
        let request = SKProductsRequest(productIdentifiers: identifiers)
        request.delegate = self
        request.start()
    }
    
    // MARK: - 购买产品
    func purchaseProduct(_ product: SKProduct) {
        guard SKPaymentQueue.canMakePayments() else {
            delegate?.purchaseCompleted(result: .failure(error: "User is prohibited from making in-app purchases"))
            return
        }
        
        let payment = SKPayment(product: product)
        SKPaymentQueue.default().add(payment)
    }
    
    // MARK: - 恢复购买
    func restorePurchases() {
        SKPaymentQueue.default().restoreCompletedTransactions()
    }
    
    // MARK: - 获取本地收据
    private func getAppStoreReceipt() -> String? {
        guard let receiptURL = Bundle.main.appStoreReceiptURL,
              let receiptData = try? Data(contentsOf: receiptURL) else {
            return nil
        }
        return receiptData.base64EncodedString()
    }
    
    // MARK: - 根据ID获取产品
    func getProduct(by identifier: String) -> SKProduct? {
        return availableProducts.first { $0.productIdentifier == identifier }
    }
    
    // MARK: - 格式化价格
    static func formatPrice(for product: SKProduct) -> String? {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        numberFormatter.locale = product.priceLocale
        return numberFormatter.string(from: product.price)
    }
}

// MARK: - SKProductsRequestDelegate
extension WJPurchaseManager: SKProductsRequestDelegate {
    
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        DispatchQueue.main.async {
            let sortedProducts = response.products.sorted { product1, product2 in
                product1.price.decimalValue > product2.price.decimalValue
            }
            self.availableProducts = sortedProducts
            self.delegate?.productsLoaded(products: sortedProducts)
            
            // 打印无效的产品ID
            if !response.invalidProductIdentifiers.isEmpty {
                print("无效的产品ID: \(response.invalidProductIdentifiers)")
            }
        }
    }
    
    func request(_ request: SKRequest, didFailWithError error: Error) {
        DispatchQueue.main.async {
            self.delegate?.productsRequestFailed(error: error.localizedDescription)
        }
    }
}

// MARK: - SKPaymentTransactionObserver
extension WJPurchaseManager: SKPaymentTransactionObserver {
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case .purchasing:
                // 购买中，不需要处理
                break
                
            case .purchased:
                // 购买成功
                handlePurchasedTransaction(transaction)
                
            case .failed:
                // 购买失败
                handleFailedTransaction(transaction)
                
            case .restored:
                // 恢复购买
                handleRestoredTransaction(transaction)
                
            case .deferred:
                // 交易延迟（需要家长批准等）
                DispatchQueue.main.async {
                    self.delegate?.purchaseCompleted(result: .failure(error: "The transaction is awaiting approval."))
                }
                
            @unknown default:
                break
            }
        }
    }
    
    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
        // 恢复购买完成
        DispatchQueue.main.async {
            self.delegate?.purchaseCompleted(result: .restored)
        }
        
        NotificationCenter.default.post(name: .purchaseRestoredNotification, object: nil)
        handleRestoredSuccess()
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
        // 恢复购买失败
        DispatchQueue.main.async {
            self.delegate?.purchaseCompleted(result: .restoreFailure(error: error.localizedDescription))
        }
    }
    
    // MARK: - 处理交易结果
    private func handlePurchasedTransaction(_ transaction: SKPaymentTransaction) {
        guard let receipt = getAppStoreReceipt() else {
            DispatchQueue.main.async {
                self.delegate?.purchaseCompleted(result: .failure(error: "The receipt cannot be obtained"))
            }
            SKPaymentQueue.default().finishTransaction(transaction)
            return
        }
        
        // 通知代理购买成功
        DispatchQueue.main.async {
            self.delegate?.purchaseCompleted(result: .success(receipt: receipt))
        }
        
        NotificationCenter.default.post(name: .purchaseSucessNotification, object: nil)
        
        handlePurchasedSuccess(transaction: transaction)
        
        // 完成交易
        SKPaymentQueue.default().finishTransaction(transaction)
    }
    
    private func handleFailedTransaction(_ transaction: SKPaymentTransaction) {
        if let error = transaction.error as? SKError {
            switch error.code {
            case .paymentCancelled:
                DispatchQueue.main.async {
                    self.delegate?.purchaseCompleted(result: .cancelled)
                }
            default:
                DispatchQueue.main.async {
                    self.delegate?.purchaseCompleted(result: .failure(error: error.localizedDescription))
                }
            }
        } else {
            DispatchQueue.main.async {
                self.delegate?.purchaseCompleted(result: .failure(error: transaction.error?.localizedDescription ?? "unkonwn error"))
            }
        }
        
        SKPaymentQueue.default().finishTransaction(transaction)
    }
    
    private func handleRestoredTransaction(_ transaction: SKPaymentTransaction) {
        SKPaymentQueue.default().finishTransaction(transaction)
    }
    
    private func handleRestoredSuccess() {
        let receipt = getAppStoreReceipt()
        WJUserManager.shared.restorePurchases(receipt: receipt) { [weak self] isVIP in
            DispatchQueue.main.async {
//                if isVIP {
//                    self?.showSuccess("恢复购买成功！")
//                    self?.updateUI()
//                } else {
//                    self?.showError("没有有效的购买记录")
//                }
            }
        }
    }

    private func handlePurchasedSuccess(transaction: SKPaymentTransaction)  {
        
        guard let transactionId = transaction.transactionIdentifier else { return }
        let productIdentifier = transaction.payment.productIdentifier
        let receipt = getAppStoreReceipt()
        
        // 处理购买成功
        WJUserManager.shared.handlePurchaseSuccess(
            productId: productIdentifier,
            transactionId: transactionId
        )
        
        // 验证状态
        WJUserManager.shared.validateAndSetVIPStatus(
            receipt: receipt,
            productId: productIdentifier
        ) { [weak self] isVIP in
            DispatchQueue.main.async {
//                if isVIP {
//                    self?.showSuccess("购买成功！")
//                    self?.updateUI()
//                }
            }
        }
    }
}
